# -*- coding: utf-8 -*-
import asyncio

import requests
import json
import re
import urllib.parse as urlparse
import threading
from datetime import datetime
import os
import chardet

'利用协程发起并发访问，如果只要拿一个结果就返回，效率并没有提高，后续如果需要等待所有结果返回的话，就可以使用'

imgname = 'hj.png'
imgpath = r'media/img/hj.png'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
}

baidu_source = 'http://image.baidu.com'
# 获取vs
vs_url = baidu_source + '/?fr=shitu'
vs_page = requests.get(vs_url, headers=headers).text
vs_id = re.findall('window.vsid = "(.*?)"', vs_page)[0]

baidu_post_url = baidu_source + \
    '/pcdutu/a_upload?fr=html5&target=pcSearchImage&needJson=true'

print('f size =', os.path.getsize(imgpath))

baidu_files = {'file': open(imgpath, 'rb'), 'pos': 'upload',
               'uptype': 'upload_pc', 'fm': 'home'}


sogou_files = {'file': open(imgpath, 'rb'), 'flag': '1'}

sogou_source = 'http://pic.sogou.com'
sogou_post_url = sogou_source + '/ris_upload'
sogou_query_url = sogou_source + '/ris?'

from aiohttp import ClientSession
import re


async def post_fetch(t, u, d):
    print('post_fetch time =', datetime.now())
    async with ClientSession() as session:
        async with session.post(u, headers=headers, data=d, timeout=20) as response:
            print('u ======================= %s  time = %s' %
                  (u, datetime.now()))
            if t == 'baidu':
                tmp = await response.text()
                print(type(tmp))
                print('tmp = ',tmp)
                tmp_json = json.loads(tmp)
                queryImageUrl = tmp_json['url']
                querySign = tmp_json['querySign']
                # simid = tmp_json['simid']
                get_rest_url = baidu_source + '/pcdutu?queryImageUrl=' + queryImageUrl + '&querySign=' + \
                    querySign + 'fm=index&uptype=upload_pc&result=result_camera&vs=' + vs_id
                
                rest = await get_fetch(get_rest_url)
                guessWord = re.findall("'guessWord': '(.*?)'", rest.decode())[0]
                print('guessword = ', guessWord)
                return guessWord
            elif t == 'sogou':
                qurl = response.url
                print('type qurl == ', type(qurl))
                print('qurl = ', qurl)

                qs = urlparse.urlparse(str(qurl)).query
                qargs = dict([(k, v[0])
                              for k, v in urlparse.parse_qs(qs).items()])
                print('args = ', qargs)

                if('query' not in qargs or 'flag' not in qargs):
                    print('url err: no query arg !')
                    return
                imgqurl = sogou_query_url + "query=" + qargs['query'] + "&dm=0&reqType=ajax&tn=0&reqForm=result"
                 
                img_result = await get_fetch(imgqurl)
                print('img_result type = %s ' % type(img_result))
                # bytes(s, encoding = "utf8")  
                print(chardet.detect(img_result))
                ss = img_result.decode(chardet.detect(img_result)['encoding'],'ignore')
                
                tj =  json.loads(ss)
                entity = tj['entity']
                print('entity =', entity)

                return entity
            # return {t: await response.read()}


async def get_fetch(u):
    async with ClientSession() as session:
        async with session.get(u, headers=headers, timeout=25) as response:
            response.encoding = 'utf-8'
            return await response.read()


async def try_get_gw():
    tasks = [
        asyncio.ensure_future(post_fetch('baidu',
                                         baidu_post_url, baidu_files)),
        asyncio.ensure_future(post_fetch('sogou',
                                         sogou_post_url, sogou_files))
    ]

    res = await asyncio.gather(*tasks)

    print('try_get_gw time ============', datetime.now())

    print(res)

print('start now  time ============', datetime.now())
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(try_get_gw())
loop.run_until_complete(future)
